package com.shuyuansystem.controller;

import com.shuyuansystem.dao.OrderMapper;
import com.shuyuansystem.entity.Result;
import com.shuyuansystem.pojo.CheckOrders;
import com.shuyuansystem.pojo.ShoppingCart;
import com.shuyuansystem.service.OrderService;
import com.shuyuansystem.service.ProductService;
import com.shuyuansystem.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private final OrderService orderService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductService productService;

    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

//    @RequestMapping("/buyProduct")
//    public ResponseEntity<Map<String, Object>> buyProduct(@RequestBody Map<String, Object> request) {
//        String productIdStr = request.get("productId").toString();
//        String token = request.get("token").toString();
//        int productId = Integer.parseInt(productIdStr);
//        Map<String, Object> result = orderService.buyProduct(productId, token);
//        HttpStatus status = (Boolean) result.get("success") ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR;
//        return new ResponseEntity<>(result, status);
//    }

    @RequestMapping("/addshoppingcart")
    public ResponseEntity<Map<String, Object>> addshoppingcart(@RequestBody Map<String, Object> request) {
        Integer productId = Integer.parseInt(request.get("productId").toString());
        Integer quantity = Integer.parseInt(request.get("quantity").toString());
        String token = request.get("token").toString();
        Integer id = Integer.parseInt(JWTUtils.getUserIdFromToken(token));
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setId(id);
        shoppingCart.setProductId(productId);
        shoppingCart.setQuantity(quantity);
        Result result = orderService.addShoppingcart(shoppingCart);
        Map<String, Object> response = new HashMap<>();
        response.put("success", result.isFlag());
        response.put("message", result.getMessage());
        response.put("newQuantity", result.getData());
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    @RequestMapping("/reduceShoppingCart")
    public ResponseEntity<Map<String, Object>> reduceShoppingCart(@RequestBody Map<String, Object> request) {
        Integer productId = Integer.parseInt(request.get("productId").toString());
        Integer quantity = Integer.parseInt(request.get("quantity").toString());
        String token = request.get("token").toString();
        Integer id = Integer.parseInt(JWTUtils.getUserIdFromToken(token));
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setId(id);
        shoppingCart.setProductId(productId);
        shoppingCart.setQuantity(quantity);
        Result result = orderService.reduceShoppingCart(shoppingCart);
        Map<String, Object> response = new HashMap<>();
        response.put("success", result.isFlag());
        response.put("message", result.getMessage());
        response.put("newQuantity", result.getData());
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    @RequestMapping ("/getShoppingCartQuantity")
    public ResponseEntity<Map<String, Object>> getShoppingCartQuantity(@RequestBody Map<String, Object> request) {
        Integer productId = Integer.parseInt(request.get("productId").toString());
        String token = request.get("token").toString();
        Integer id = Integer.parseInt(JWTUtils.getUserIdFromToken(token));
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setId(id);
        shoppingCart.setProductId(productId);
        Integer quantity = orderService.getShoppingCartQuantity(shoppingCart);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("quantity", quantity);
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
    @RequestMapping("/getOrder")
    public Map<String, List<CheckOrders>> getOrderById(@RequestBody Map<String, Object> request) {
        try {
            String token = request.get("token").toString();
            String userId = JWTUtils.getUserIdFromToken(token);

            // 获取购物车信息
            Map<Integer, Integer> productIdToQuantityMap = getProductIdAndQuantityMap(userId);
            // 过滤掉数量为 0 的商品
            productIdToQuantityMap.values().removeIf(quantity -> quantity == 0);

            // 获取产品 ID 列表
            List<Integer> productIds = new ArrayList<>(productIdToQuantityMap.keySet());
            // 获取商家 - 产品关系信息
            List<Map<String, Object>> merchantProductAssociations = orderMapper.getMerchantProductAssociationByProductIds(productIds);
            // 按 Merchant ID 分组
            Map<String, List<CheckOrders>> merchantIdToCheckOrdersMap = groupByMerchantId(productIdToQuantityMap, merchantProductAssociations, userId);

            // 检查订单表中存在但购物车中不存在的商品，并删除订单表中的对应记录
            deleortherOrderOrderList(userId);

            // 插入或更新订单信息到数据库
            insertOrUpdateOrders(merchantIdToCheckOrdersMap);

            return merchantIdToCheckOrdersMap;
        } catch (Exception e) {
            // 处理异常，可根据实际情况记录日志或返回错误信息
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    /**
     * 获取购物车中产品 ID 及其数量的映射
     *
     * @param userId 用户 ID
     * @return 产品 ID 及其数量的映射
     */
    private Map<Integer, Integer> getProductIdAndQuantityMap(String userId) {
        List<ShoppingCart> shoppingCartsList = orderMapper.getProductIdAndQuantityById(userId);
        Map<Integer, Integer> productIdToQuantityMap = new HashMap<>();
        for (ShoppingCart shoppingCart : shoppingCartsList) {
            Integer productId = shoppingCart.getProductId();
            Integer quantity = shoppingCart.getQuantity();
            productIdToQuantityMap.put(productId, quantity);
        }
        return productIdToQuantityMap;
    }

    /**
     * 按 Merchant ID 分组
     *
     * @param productIdToQuantityMap 产品 ID 及其数量的映射
     * @param merchantProductAssociations 商家 - 产品关系信息
     * @param userId 用户 ID
     * @return 按 Merchant ID 分组的 CheckOrders 列表
     */
    private Map<String, List<CheckOrders>> groupByMerchantId(Map<Integer, Integer> productIdToQuantityMap, List<Map<String, Object>> merchantProductAssociations, String userId) {
        Map<String, List<CheckOrders>> merchantIdToCheckOrdersMap = new HashMap<>();
        for (Map<String, Object> association : merchantProductAssociations) {
            String merchantId = association.get("merchant_id").toString();
            Integer productId = (Integer) association.get("product_id");
            Integer quantity = productIdToQuantityMap.get(productId);
            String productName = productService.getProductNameById(productId);
            CheckOrders checkOrders = new CheckOrders();
            checkOrders.setUser_id(userId);
            checkOrders.setMerchant_id(merchantId);
            checkOrders.setProduct_name(productName);
            checkOrders.setQuantity(quantity);
            // 根据 product_id 获取对应的价格
            BigDecimal price = productService.getProductPriceById(productId);
            if (price != null) {
                // 计算总价
                double totalPrice = price.doubleValue() * quantity;
                checkOrders.setTotal_price(totalPrice);
            } else {
                // 如果价格获取失败，总价设为 0
                checkOrders.setTotal_price(0);
            }
            merchantIdToCheckOrdersMap.computeIfAbsent(merchantId, k -> new ArrayList<>()).add(checkOrders);
        }
        return merchantIdToCheckOrdersMap;
    }

    private void insertOrUpdateOrders(Map<String, List<CheckOrders>> merchantIdToCheckOrdersMap) {
        for (List<CheckOrders> checkOrdersList : merchantIdToCheckOrdersMap.values()) {
            for (CheckOrders checkOrders : checkOrdersList) {
                if (checkOrders.getQuantity() > 0) {
                    // 检查指定 user_id、merchant_id、product_name 且 merchant_order_number 为空的记录是否存在
                    boolean orderExists = orderMapper.checkOrderExists(checkOrders);
                    if (orderExists) {
                        // 如果存在，更新数据
                        orderMapper.updateCheckOrders(checkOrders);
                    } else {
                        // 如果不存在，插入数据并将 merchant_order_number 设置为空
                        checkOrders.setMerchant_order_number("");
                        orderMapper.insertOrderList(List.of(checkOrders));
                    }
                }
            }
        }
    }

    private void checkAndDeleteOrders(Map<String, List<CheckOrders>> merchantIdToCheckOrdersMap, String userId) {
        // 获取订单表中所有用户的订单信息
        List<CheckOrders> allOrders = orderMapper.getOrdersByUserId(userId);

        // 构建购物车中商品的标识集合（商家ID:商品名称）
        Set<String> cartProductIdentifiers = new HashSet<>();
        for (List<CheckOrders> checkOrdersList : merchantIdToCheckOrdersMap.values()) {
            for (CheckOrders checkOrders : checkOrdersList) {
                String identifier = checkOrders.getMerchant_id() + ":" + checkOrders.getProduct_name();
                cartProductIdentifiers.add(identifier);
            }
        }

        // 遍历订单表中的订单，检查是否有购物车中已不存在的商品
        for (CheckOrders order : allOrders) {
            String identifier = order.getMerchant_id() + ":" + order.getProduct_name();
            if (!cartProductIdentifiers.contains(identifier)) {
                // 如果购物车中已不存在该商品，删除订单表中的记录
                orderMapper.deleteOrder(order);
            }
        }

    }
    public void deleortherOrderOrderList(String userId) {
//        String userId = "28";
        List<ShoppingCart> shoppingCarts = orderService.getShoppingCartProductIdsByUserId(userId);

        // 存储购物车中商家 ID 和商品名称的组合
        Set<String> cartMerchantProductSet = new HashSet<>();

        if (shoppingCarts != null && !shoppingCarts.isEmpty()) {
            List<Integer> productIds = new ArrayList<>();
            for (ShoppingCart cart : shoppingCarts) {
                int productId = cart.getProductId();
                productIds.add(productId);
                System.out.println("用户 ID: " + userId + " 对应的购物车产品 ID: " + productId);
            }

            // 根据产品 ID 列表查询对应的商家 ID
            List<Map<String, Object>> merchantIds = orderService.getMerchantIdsByProductIds(productIds);

            if (merchantIds != null && !merchantIds.isEmpty()) {
                for (Map<String, Object> merchant : merchantIds) {
                    int merchantId = (int) merchant.get("merchant_id");
                    int productId = (int) merchant.get("product_id");
                    System.out.println("产品 ID: " + productId + " 对应的商家 ID: " + merchantId);
                }
            } else {
                System.out.println("未找到这些产品 ID 对应的商家 ID。");
            }

            // 根据产品 ID 列表查询对应的产品名称
            List<Map<String, Object>> productNames = orderService.getProductNamesByProductIds(productIds);
            Map<Integer, String> productIdToNameMap = new HashMap<>();
            for (Map<String, Object> product : productNames) {
                int productId = (int) product.get("product_id");
                String productName = (String) product.get("product_name");
                productIdToNameMap.put(productId, productName);
                System.out.println("产品 ID: " + productId + " 对应的产品名称: " + productName);
            }

            // 创建一个数组来保存产品 ID、商家 ID 和产品名称
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (Map<String, Object> merchant : merchantIds) {
                int productId = (int) merchant.get("product_id");
                int merchantId = (int) merchant.get("merchant_id");
                String productName = productIdToNameMap.get(productId);

                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("productId", productId);
                resultMap.put("merchantId", merchantId);
                resultMap.put("productName", productName);
                resultList.add(resultMap);

                // 将商家 ID 和商品名称的组合添加到集合中
                cartMerchantProductSet.add(merchantId + ":" + productName);
            }

            // 打印结果数组
            System.out.println("产品 ID、商家 ID 和产品名称的结果数组:");
            for (Map<String, Object> result : resultList) {
                System.out.println(result);
            }
        } else {
            System.out.println("用户 ID: " + userId + " 的购物车为空。");
        }

        // 获取 order_list 表中所有的商家 ID 及对应的商品名称
        List<Map<String, Object>> merchantAndProductList = orderService.getMerchantIdAndProductNameFromOrderList();

        // 存储订单表中有但购物车中没有的商家 ID 和商品名称
        List<Map<String, Object>> differenceList = new ArrayList<>();

        if (merchantAndProductList != null && !merchantAndProductList.isEmpty()) {
            System.out.println("商家 ID 及对应的商品名称数组:");
            for (Map<String, Object> entry : merchantAndProductList) {
                String merchantId = (String) entry.get("merchant_id");
                String productName = (String) entry.get("product_name");
                System.out.println("商家 ID: " + merchantId + ", 商品名称: " + productName);

                // 检查该组合是否在购物车集合中
                if (!cartMerchantProductSet.contains(merchantId + ":" + productName)) {
                    Map<String, Object> diffMap = new HashMap<>();
                    diffMap.put("merchantId", merchantId);
                    diffMap.put("productName", productName);
                    differenceList.add(diffMap);
                }
            }
        } else {
            System.out.println("order_list 表中没有数据。");
        }

        // 打印订单表中有但购物车中没有的商家 ID 和商品名称
        if (!differenceList.isEmpty()) {
            System.out.println("订单表中有但购物车中没有的商家 ID 和商品名称:");
            for (Map<String, Object> diff : differenceList) {
                System.out.println("商家 ID: " + diff.get("merchantId") + ", 商品名称: " + diff.get("productName"));
            }

            // 调用删除方法删除订单表中多余的记录
            int deletedCount = orderService.deleteOrdersByMerchantAndProduct(differenceList);
            System.out.println("成功删除 " + deletedCount + " 条订单记录。");
        } else {
            System.out.println("订单表中的商品在购物车中都存在。");
        }
    }
}